﻿using Core.SimpleTemp.Common;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.SimpleTemp.Application.ZY
{
    [AutoDi()]
    public class ZYSservice
    {
        private static object obj = new object();
        readonly CoreDBContext _coreDBContext;
        public ZYSservice(CoreDBContext coreDBContext)
        {
            _coreDBContext = coreDBContext;
        }

        public int GetTicketNumber(TicketTypeEnum ticketType)
        {
            int number;
            lock (obj)
            {
                var nowDay = DateTime.Now.ToString("yyyy-MM-dd");
                var numberEntity = _coreDBContext.ZY_Number.Where(entity => entity.TableType == ticketType.ToString() && entity.NumberDate == nowDay).SingleOrDefault();
                if (numberEntity == null)
                    numberEntity = _coreDBContext.ZY_Number.Add(new ZY_Number()
                    {
                        Number = 0,
                        NumberDate = nowDay,
                        TableType = ticketType.ToString()
                    }).Entity;
                else
                {
                    numberEntity.Number++;
                }
                number = numberEntity.Number;
                _coreDBContext.SaveChanges();
            }
            return number;
        }

        public string CreateTicketNumber(TicketTypeEnum ticketType, Guid userId)
        {
            int number = GetTicketNumber(ticketType);
            var strNumber = number.ToString().PadLeft(4, '0');
            var nowDay = DateTime.Now.ToString("yyyyMMdd");
            var userDepartmentDuty = _coreDBContext.SysUserDepartmentDuty.Where(a => a.SysUserInforID == userId).FirstOrDefault();
            if (userDepartmentDuty == null || userDepartmentDuty.SysDepartmentID == null)
                throw new CustomOperationException("生成票证编号失败：当前用户下为设置部门信息");
            var deparment = _coreDBContext.SysDepartment.Where(a => a.Id == userDepartmentDuty.SysDepartmentID).FirstOrDefault();
            if (deparment == null)
                throw new CustomOperationException($"生成票证编号失败：为找对ID为{userDepartmentDuty.SysDepartmentID}的部门信息");
            var departmentCode = deparment.Code;
            return departmentCode + nowDay + strNumber;
        }



    }
}
